# -*-coding: utf-8 -*-
#引入socket库
import socket
# https://blog.csdn.net/qq_51652864/article/details/115559860
import sys
import time

import ecal.core.core as ecal_core
from ecal.core.subscriber import ProtoSubscriber

# Import the "hello_world_pb2.py" file that we have just generated from the
# proto_messages directory 
import control_pb2 as control


#这是进行定义一个ip协议版本AF_INET（IPv4），定义一个传输TCP协议，SOCK_STREAM
sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#定义ip地址与端口号，ip地址就是服务端的ip地址，端口随便定义，但要与客户端脚本一致
ip_port=('0.0.0.0',1234)
#绑定一个端口
sk.bind(ip_port)
#监听一个端口,这里的数字3是一个常量，表示阻塞3个连接，也就是最大等待数为3
sk.listen(3)
#接受客户端的数据，并返回两个参数，a为连接信息，b为客户端的ip地址与端口号
client,b=sk.accept()
print(client)

def init_socket():
    pass
    # while True:
    #     data=client.recv(1024)#客户端发送的数据存储在recv里，1024指最大接受数据的量
    #     print(data.decode('utf-8'))
    #     message=input("you can say:")
    #     client.send(message.encode('utf-8'))
    #     if message==('bye'):
    #         break

a_str = 0
def sand_socket_message(data_a,data_b):
    data1 = str(data_a)
    data2 = str(data_b)
    a_str = "~"+data1+","+data2
    print(a_str)
    client.send(a_str.encode('utf-8'))

# Callback for receiving messages
def callback(topic_name, controlMoveOrder_msg, time):
  #print(controlMoveOrder_msg.lineSpeed, controlMoveOrder_msg.angularSpeed)
  #try:
  sand_socket_message(controlMoveOrder_msg.lineSpeed, controlMoveOrder_msg.angularSpeed)
  #except:
  #   print("wait")


if __name__ == "__main__":
  # initialize eCAL API. The name of our Process will be
  # "Python Protobuf Subscriber"
  ecal_core.initialize(sys.argv, "Python Protobuf Subscriber")

  # Create a Protobuf Publisher that publishes on the topic
  # "hello_world_python_protobuf_topic". The second parameter tells eCAL which
  # datatype we are expecting to receive on that topic.
  sub = ProtoSubscriber("chessMessage" , control.controlMoveOrder)

  # Set the Callback
  sub.set_callback(callback)
  init_socket()
  # Just don't exit
  while ecal_core.ok():
    time.sleep(0.5)
  
  # finalize eCAL API
  ecal_core.finalize()